package org.shreker.shan.core.service.impl;

import java.util.Date;
import org.shreker.shan.core.domain.Account;
import org.shreker.shan.core.domain.Login;
import org.shreker.shan.core.domain.User;
import org.shreker.shan.core.exception.UserException;
import org.shreker.shan.core.mapper.LoginMapper;
import org.shreker.shan.core.service.IAccountService;
import org.shreker.shan.core.service.ILoginService;
import org.shreker.shan.core.service.IUserService;
import org.shreker.shan.core.util.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

	@Autowired
	private LoginMapper loginMapper;
	
	// 不要直接去操作Mapper
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IAccountService accountService;
	
	public void register(String username, String password, Integer identity) throws Exception {
		Login login = loginMapper.selectUserByUsername(username);
		if (login == null) { // 用户名不存在
			// 保存一个新的登录信息到登录表中
			login = new Login();
			login.setIdentity(identity);
			login.setUsername(username);
			login.setPassword(password);
			loginMapper.insert(login);
			
			// 创建用户信息
			User user = new User();
			user.setId(login.getId());
			user.setBitState(0L);
			userService.save(user);
			
			// 创建账户信息
			Account account = new Account();
			account.setId(login.getId());
			account.initAccount();
			accountService.save(account);
		} else {
			throw new UserException("用户名已存在!");
		}
	}

	public void login(String username, String password, Integer identity) throws Exception {
		Login login = loginMapper.selectLogin(username, password, identity);
		if (login == null) { // 用户名或密码错误
			throw new UserException("用户名或密码错误");
		} else { // 成功
			// 如果登录成功, 把用户的信息添加到Session中
			login.setLoginDate(new Date());
			loginMapper.updateByPrimaryKey(login);
			LoginContext.setCurrentLogin(login);
		}
	}

	@Override
	public void save(Login login) throws Exception {
		loginMapper.insert(login);
	}

	@Override
	public Long selectCountByIdentity(Integer identity) {
		return loginMapper.selectCountByIdentity(identity);
	}
	
}
